<template>
  <!-- 电池堆策略详情与下发 -->
  <div class="issuedDetial">
    <a-divider
      orientation="left"
      :dashed="true"
      style="font-size: 20px"
      v-if="!isDetial"
      >策略下发信息</a-divider
    >
    <a-divider orientation="left" :dashed="true" style="font-size: 20px" v-else
      >{{ linkName }}策略下发详情</a-divider
    >
    <div class="chartInf">
      <div class="leftCon">
        <div class="button-group" v-if="!isDetial">
          <template v-if="!isDisable">
            <a-button
              type="primary"
              class="save-btn"
              @click="issued"
              size="small"
              style="margin-right: 10px; font-size: 12px"
              >保存并下发</a-button
            >
            <a-button
              class="cancel-btn greenpPlainBtn"
              size="small"
              style="margin-right: 10px; font-size: 12px"
              @click="cancel"
              >取消编辑</a-button
            >
          </template>
          <a-button
            type="primary"
            class="edit greenBtn"
            @click="edit"
            size="small"
            style="margin-right: 10px; font-size: 12px"
            v-else
            >编辑</a-button
          >

          <a-button
            type="link"
            class="copy-btn bluePlainBtn"
            size="small"
            style="margin-right: 10px; font-size: 12px"
            v-if="filterForm.strategyList.length != 0"
            @click="copyStrategy"
            :disabled="isDisable"
            >复制策略</a-button
          >
          <a-button
            type="link"
            class="paste-btn bluePlainBtn"
            size="small"
            style="margin-right: 10px; font-size: 12px"
            v-if="copiedStrategy"
            :disabled="isDisable"
            @click="pasteStrategy"
            >粘贴策略</a-button
          >
        </div>
        <a-row>
          <a-col :span="isDetial ? 6 : 5"
            ><div class="gridHead">开始时间</div></a-col
          >
          <a-col :span="isDetial ? 6 : 5"
            ><div class="gridHead">结束时间</div></a-col
          >
          <a-col :span="6"><div class="gridHead">有功功率(KW)</div></a-col>
          <a-col :span="isDetial ? 6 : 5"
            ><div class="gridHead">SOC限制值(%)</div></a-col
          >
          <a-col :span="3"
            ><div class="gridHead" v-if="!isDetial">操作</div></a-col
          >
        </a-row>
        <a-row v-if="filterForm.strategyList.length === 0">
          <a-col :span="24">
            <div
              style="
                height: calc(100vh - 530px);
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <a-empty :image="simpleImage" /></div
          ></a-col>
        </a-row>
        <a-row v-for="(item, idx) in filterForm.strategyList" :key="idx" v-else>
          <a-col :span="isDetial ? 6 : 5"
            ><div class="gridContent">
              <a-time-picker
                v-model:value="item.start"
                valueFormat="HH:mm:ss"
                format="HH:mm"
                placeholder="请选择开始时间"
                :disabled="isDisable"
                size="small"
                style="width: 85%"
              /></div
          ></a-col>
          <a-col :span="isDetial ? 6 : 5"
            ><div class="gridContent">
              <a-time-picker
                v-model:value="item.end"
                placeholder="请选择结束时间"
                valueFormat="HH:mm:ss"
                format="HH:mm"
                size="small"
                style="width: 85%"
                :disabled="isDisable"
                @blur="setNextStart(idx)"
              /></div
          ></a-col>
          <a-col :span="6"
            ><div class="gridContent">
              <a-input
                v-model:value="item.activePower"
                placeholder="请输入有功功率(正充负放)"
                allow-clear
                style="width: 85%"
                size="small"
                @blur="check(item.activePower, idx)"
                :disabled="isDisable"
              /></div
          ></a-col>
          <a-col :span="isDetial ? 6 : 5"
            ><div class="gridContent">
              <a-input
                v-model:value="item.socLimit"
                placeholder="soc限制值"
                allow-clear
                style="width: 85%"
                size="small"
                :disabled="isDisable || socLimitDisabled"
              /></div
          ></a-col>
          <a-col :span="3" v-if="!isDetial">
            <div class="gridContent icon" v-if="!isDisable">
              <PlusCircleOutlined
                @click="addStrategy"
                v-if="idx === 0"
                style="color: greenyellow"
              />
              <MinusCircleOutlined
                v-else
                style="color: red"
                @click="deleteRow(idx)"
              />
            </div>
          </a-col>
        </a-row>
      </div>
      <div class="rightCon">
        <a-empty
          :image="simpleImage"
          v-if="filterForm.strategyList.length === 0"
        />
        <div ref="strategyChart" id="strategyChart" class="chrat" v-else></div>
      </div>
    </div>
  </div>
</template>
<script setup>
// 
import { Empty } from 'ant-design-vue'
import moment from "moment"
import * as echarts from "echarts"
import StrategyChart from "./chartOption"
const $api = inject("$api")
const simpleImage = ref(Empty.PRESENTED_IMAGE_SIMPLE)
const props = defineProps({
  linkDeviceId: {
    type: Number,
    default: null,
  },
  isDetial: {
    type: Boolean,
    default: false,
  },
  rowDataId: {
    type: Number,
    default: null,
  },
  stationInfo: {
    type: Object,
    default: () => ({}),
  },
})

const socLimitDisabled = computed(() => {
  // 如果电站是集装箱电站，则soc限制值不可编辑
  return props.stationInfo?.isContainer
})

// 复制的策略内容
const copiedStrategy = ref(null)

// 复制策略
const copyStrategy = () => {
  copiedStrategy.value = JSON.parse(
    JSON.stringify(filterForm.value.strategyList)
  )
  message.success("策略复制成功")
}

// 粘贴策略
const pasteStrategy = () => {
  if (copiedStrategy.value) {
    filterForm.value.strategyList = JSON.parse(
      JSON.stringify(copiedStrategy.value)
    )
    message.success("策略粘贴成功")
    isDisable.value = false
    getChart()
  }
}

const filterForm = ref({
  stationId: null,
  linkDeviceId: null,
  strategyList: [
    {
      start: "00:00:00",
      end: "00:00:00",
      activePower: "",
      socLimit: "",
    },
  ],
})
watch(
  () => props.linkDeviceId,
  async (val) => {
    if (val) {
      isDisable.value = true
      filterForm.value.linkDeviceId = val
    }
  }
)
const rowDataId = ref(null)
watch(
  () => props.rowDataId,
  async (val) => {
    if (val) {
      rowDataId.value = val
    }
  }
)
//请求电池堆
const linkName = ref(null)
const emit = defineEmits(["loading-change"])
const getChargeStrategyDetail = async (id) => {
  emit("loading-change", true)
  const res = await $api.chargeStrategyDetail({
    id: id,
  })
  if (res && res.code === 0) {
    linkName.value = res.data.linkName || ""
    filterForm.value.strategyList = JSON.parse(res.data.publishValue)
    if (filterForm.value.strategyList.length === 0) {
      emit("loading-change", false)
      return
    }
    await nextTick()
    getChart()
  }
  emit("loading-change", false)
}
//请求最新策略
const getChargeStrategyLastDetail = async (id) => {
  emit("loading-change", true)
  const res = await $api.getLastDetail({
    linkDeviceId: id,
  })
  if (res && res.code === 0) {
    filterForm.value.strategyList = res.data.strategyList
    if (filterForm.value.strategyList.length === 0) {
      emit("loading-change", false)
      return
    }
    await nextTick()
    getChart()
  }
  emit("loading-change", false)
}
//添加策略集合
const addStrategy = () => {
  let list = filterForm.value.strategyList
  let prevStar = list.length > 0 ? list[list.length - 1].end : "00:00:00"
  list.push({
    start: prevStar,
    end: "",
    activePower: "",
    socLimit: "",
  })
}
//删除时间段
const deleteRow = (idx) => {
  let list = filterForm.value.strategyList
  if (list.length === 1) {
    message.error("需至少填一条数据")
    return
  }
  list.splice(idx, 1)
}
//编辑策略
const isDisable = ref(true)
const edit = () => {
  if (filterForm.value.strategyList.length === 0) {
    addStrategy()
  }
  isDisable.value = false
}
//取消策略修改
const cancel = () => {
  //getChargeStrategyDetail(props.linkDeviceId)
  getChargeStrategyLastDetail(props.linkDeviceId)
  isDisable.value = true
}
//图表初始化
/* const getChargestrategyList = async (id) => {
  let res = await $api.chargeStrategyDetail({
    linkDeviceId: id,
  })
  filterForm.value.strategyList = res.data.strategyList
  await nextTick()
  getChart()
} */
//设置结束时候失焦后赋值给下一行的开始时间
const setNextStart = (idx) => {
  let list = filterForm.value.strategyList
  if (idx === list.length - 1) {
    return
  }
  list[idx + 1].start = list[idx].end
  getChart()
}
//请求图表数据
const getChart = () => {
  const baseDate = moment().format("YYYY-MM-DD")
  let list = filterForm.value.strategyList.map((item, idx) => {
    item.chartEnd = item.end
    if (item.start !== "00:00:00" && item.end === "00:00:00") {
      item.chartEnd = "23:59:59"
    }
    let { start, end, activePower, chartEnd } = item

    return {
      value: [
        `${baseDate} ${start}`,
        `${baseDate} ${chartEnd}`,
        activePower,
        item,
      ],
    }
  })
  StrategyChart.series[0].data = list
  let chartDom = document.getElementById(`strategyChart`)
  let myChart = echarts.init(chartDom)
  myChart.setOption(StrategyChart)
}
//可填最大功率查询
const check = async (item, idx) => {
  if (item) {
    let res = await $api.checkDemand({
      linkDeviceId: filterForm.value.linkDeviceId,
      kw: item,
    })
    if (res && res.code === 0) {
      getChart()
    } else {
      filterForm.value.strategyList[idx].activePower = null
    }
  }
}
//策略下发
const issued = async () => {
  const { stationId, ...other } = filterForm.value
  let status = await $api.chargeStrategyPublish(other)
  if (status.code === 0) {
    message.success("操作成功")
    isDisable.value = true
    //getChargeStrategyDetail(props.linkDeviceId)
    getChargeStrategyLastDetail(props.linkDeviceId)
  } else {
    message.error("发布出错，请稍后重试")
  }
}
onMounted(async () => {})
defineExpose({ getChargeStrategyDetail, getChargeStrategyLastDetail })
</script>

<style lang="less" scoped>
.issuedDetial {
  /*  background-color: #141414;
  padding: 30px; */
  margin-top: 60px;
  .title {
    font-size: 22px;
  }
  /* .baseInf {
    //display: flex;
    margin-top: 20px;
  }
  .infItem {
    flex: 1;
    span {
      color: greenyellow;
    }
  } */
  .chartInf {
    margin-top: 30px;
    display: flex;
    .leftCon {
      flex: 1;
      border: 1px dashed #ccc;
      padding: 10px;
      margin-right: 20px;
      min-height: calc(100vh - 380px);
    }
    .rightCon {
      flex: 1;
      border: 1px dashed #ccc;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .gridHead {
    text-align: center;
    font-size: 16px;
    margin-top: 10px;
  }
  .gridContent {
    text-align: center;
    margin-top: 15px;
    &.icon {
      font-size: 14px;
    }
  }
  .button-group {
    display: flex;
    justify-content: end;
    margin-bottom: 10px;
  }
  .chrat {
    width: 100%;
    height: calc(100vh - 380px);
  }
}
</style>
